package camid.services.nodemanager.observers;

import java.util.concurrent.atomic.AtomicInteger;

import camid.distribution.events.InvokerEvent;
import camid.distribution.events.TimerEvent;
import camid.services.nodemanager.NodeManager;
import camid.util.monitoring.Metric;

public class InvokerObserver extends AbstractNodeObserver {

	private AtomicInteger invocationCounter;
	
	private Metric throughputMetric;
	private Metric responseTimeMetric;

	public InvokerObserver()
	{
		invocationCounter = new AtomicInteger(0);
		throughputMetric = new Metric();
		responseTimeMetric = new Metric();
	}
	
	@Override
	public void update(NodeManager nm, Object event) 
	{
		if(event instanceof InvokerEvent)
		{
			InvokerEvent ie = (InvokerEvent) event;
			invocationCounter.incrementAndGet();
			Double timespent = ie.getTimeSpent().doubleValue();
			responseTimeMetric.addMetric(timespent);
			nm.setResponseTime( responseTimeMetric.average() );
		}
		if(event instanceof TimerEvent)
		{
			Integer numberOfInvocations = invocationCounter.get();
			throughputMetric.addMetric(numberOfInvocations.doubleValue());
			nm.setThroughput( throughputMetric.average() ); 
		}
	}

}
